

/*global window, $, air, JSLINT, fDate, console */

(function(){
	
	window.trace = function(arg){
		if (typeof air !== "undefined" && air.trace) {
			air.trace.apply(air, [arg]);
		}
		else if (typeof console !== "undefined" && console.log) {
			console.log.apply(console, arguments);
		}
	};

	var interval,
		resizeTimeout;
	
	
		
	function startLint() {
		trace("start interval");
		if (interval) { clearInterval(interval); }
		CL.checkLint(true);
		
		if (CL.linting) {
			refreshList();
			resize();
			interval = setInterval(
				function(){
					CL.checkLint(false);
					refreshList();
				}, 30 * 1000);
		}
	}
	
	
	// updates UI file list
	function refreshList() {
		trace("refresh list");
		var selectedFile = $("#files tr.selected").data("url"), // preserve selected file
			$selectedRow,
			$tbody = $("#files table tbody").empty();
		for(var f in CL.lint) {
			var lint = CL.lint[f],
				file = CL.files[f];
				
			// create a new row
			var $tr = $("<tr/>")
				.append($("<td/>").text(file.friendlyUrl).addClass("file").attr("title",f))
				.append($("<td/>").text(lint.valid && "0" || lint.errors.length))
				.append($("<td/>").text(fDate.format(file.modDate, "MM/dd/yyyy hhh:mm:ss")))
				.addClass(lint.valid && "valid" || "invalid")
				.data("url",f);
			
			// preserve selected file
			if (f === selectedFile) { $selectedRow = $tr; }	
			$tbody.append($tr);
		}
		// show lint for first/selected file
		$("#files table tbody tr:even").addClass("alt");
		if(typeof $selectedRow === "undefined") { $selectedRow = $("#files table tbody tr:first"); }
		showLint($selectedRow);
	}
	
	// show errors in results area
	function showLint($row) {
		$("#files table tbody tr").removeClass("selected");
		$row.addClass("selected");
		var $results = $("#results ul").empty();
		
		if ($row.hasClass("valid")) {
			// no lint. tell the user
			$results.html("<li>Lint free!!</li>");
		}
		else if ($row.hasClass("invalid")) {
			// lint found. show the user
			var errors = CL.lint[$row.data("url")].errors;
			if(errors !== false) {
				for(var i = 0; i < errors.length; i += 1) {
					var lint = errors[i];
					if (lint) {
						$results.append(
							$("<li/>").text(["line ", lint.line, " char ", lint.character, " ", lint.reason].join(''))
						);
					}
				}
				$results.find("li").click(function(ev){
					trace("error details");
					$(this).toggleClass("selected");
					// show error details
				});
			}
		}
	}
	
	
	
	
	
	function resize() {
		var sHeight = $("#status").outerHeight(),
			wHeight = $(window).height(),
			fHeight = $("#files").outerHeight();
		$("#splash").height(wHeight-sHeight);
		$("#settings").height(wHeight-sHeight);
		$("#results").height(wHeight-sHeight-fHeight);
	}
	
	
	$(function(){

		// Quit event
		$(".quit").click(function(ev){
			window.close();
		});
		// Resize
		$(window).resize(function(ev) {
			if(resizeTimeout) { clearTimeout(resizeTimeout); }
			resizeTimeout = setTimeout(resize, 100);
		});
		// Toggle config
		$(".config, button").click(function(ev){
			if (CL.linting) {
				if ($(".config").hasClass("selected")) {
					refreshList();
					CL.checkLint(true);
				}
				$("#main").toggle();
			}
			else {
				$("#splash").toggle();
			}
			$("#settings").toggle();
			$(".config").toggleClass("selected");
		});
		// Show file lint
		$("#files table tbody tr").live("click", function(ev){
			showLint($(this));
		});
		// dragging
		$(document.body).bind("dragenter dragover", function(ev){
			ev.preventDefault();
		});
		
		// Dropping
		// we cant use jquery event binding here because jquery does
		//   not send the dataTransfer object through with the event
		document.body.ondrop = function(ev){
			trace("drop");
			var type = "application/x-vnd.adobe.air.file-list";
			var data = ev.dataTransfer.getData(type);
			for(var i = 0; i < data.length; i += 1) {
				trace(data[i]);
				CL.addWatchedPath(data[i]);
			}
			startLint();
			$("#splash").hide();
			$("#settings").hide();
			$("#main").show();
		};


		// add option checkboxes to settings
		var selectedOpts = [];
		for (var i = 0; i < CL.optionDefinitions.length; i++) {
			(function(def){
				var $li = $("<li></li>"),
					$cb = $("<input />").attr("type", "checkbox").attr("value",def.id);
					
				$li.append($cb).append(def.desc);
				
				if (i < CL.optionDefinitions.length / 2) {
					$("#options ul:first").append($li);
				}
				else {
					$("#options ul:last").append($li);
				}
				
				if (def.enabled) { selectedOpts.push(def.id); }
				//boolOptions[def.id] = def.enabled;
			})(CL.optionDefinitions[i]);
		}
		// setup check events
		$("#options input[type=checkbox]").click(function(ev){
			CL.setOption(this.value, this.checked);
		});
		
		// select default checkboxes
		$("input[type='checkbox']").val(selectedOpts);
		
	});
})();